#define _DEFAULT_SOURCE

#include <math.h>
#include <stdio.h>
#include <string.h>

#define COMMAND_SIZE 128
#define RESPONCE_SIZE 2048
#define AMOUNT_TESTS 43

int run_test(char* filename);

int main() {
  char tests[AMOUNT_TESTS][COMMAND_SIZE] = {
      "str test_files/2",
      "-n str test_files/2",
      "-o str test_files/2",
      "-on str test_files/2",
      "'5 e' test_files/2",
      "-n '5 e' test_files/2",
      "i test_files/1 test_files/2",
      "i test_files/1",
      "-c str test_files/2",
      "-c str test_files/1 test_files/2",
      "-c -f file test_files/2",
      "-c -f file test_files/1 test_files/2",
      "-i str test_files/2",
      "-i str test_files/1 test_files/2",
      "-c i test_files/1 test_files/2",
      "-v str test_files/2",
      "-vn str test_files/2",
      "-v i test_files/1 test_files/2",
      "-v i test_files/1",
      "-e str -vn test_files/2",
      "-e i -v test_files/1 test_files/2",
      "-e i -v test_files/1",
      "-e str -n test_files/2",
      "-e i test_files/1 test_files/2",
      "-e i test_files/1",
      "-vc str test_files/2",
      "-vc str test_files/1 test_files/2",
      "-vc i test_files/1 test_files/2",
      "-s str test_files/2 no_such_file",
      "str test_files/3",
      "-n str test_files/3",
      "i test_files/3 test_files/2",
      "i test_files/3",
      "-c str test_files/3",
      "-c str test_files/3 test_files/2",
      "-c -f file test_files/2",
      "-c -f file test_files/3 test_files/2",
      "-i str test_files/2",
      "-i str test_files/3 test_files/2",
      "-l -f file test_files/2",
      "-l -f file test_files/1 test_files/2",
      "-l str test_files/2",
      "-l str test_files/3 test_files/2",
  };
  int counter = 0;
  for (int i = 0; i < AMOUNT_TESTS; i++) {
    counter += run_test(tests[i]);
  }
  printf("Correct tests: %d/%d\n", counter, AMOUNT_TESTS);
  return 0;
}

int run_test(char* command) {
  int responce = 0;
  char correct_responce[RESPONCE_SIZE] = "";
  char test_responce[RESPONCE_SIZE] = "";
  char correct_command[COMMAND_SIZE];
  char test_command[COMMAND_SIZE];

  // make command
  strcpy(correct_command, "grep ");
  strcpy(test_command, "./s21_grep ");
  strcat(correct_command, command);
  strcat(test_command, command);
  // run correct
  FILE* pf = popen(correct_command, "r");
  fread(correct_responce, sizeof(char), RESPONCE_SIZE, pf);
  pclose(pf);
  // run mine
  pf = popen(test_command, "r");
  fread(test_responce, sizeof(char), RESPONCE_SIZE, pf);
  pclose(pf);
  // result
  if (strcmp(test_responce, correct_responce) == 0) {
    responce = 1;
  } else {
    printf("Fail:\n");
    printf("correct command: %s\n", (correct_command));
    printf("correct data: %s\n", (correct_responce));
    printf("your command: %s\n", (test_command));
    printf("your data: %s\n", (test_responce));
    responce = 0;
  }
  return responce;
}